import { FileEntity } from '@/entity/file.entity';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { FileService } from '../fileService';
import { config } from '@/config/';
import { uploadWithQiniu, deleteWithQinniu } from '@/utils/qiniu';
import { generateFileName } from '@/utils/generateFileName';
import { pageRecords } from '@/interface/pageInterface';
const { fileConf, page } = config;
// TODO 后续根据登录信息里获取到来，而不是写死
const fileName = generateFileName('admin');
@Injectable()
export class FileServiceImpl implements FileService {
  constructor(
    @InjectRepository(FileEntity)
    private FileRepository: Repository<FileEntity>,
  ) {}
  async list(body): Promise<pageRecords<FileEntity>> {
    let { urls, pageInfo } = body;
    const where = urls ? { id: In(urls) } : {};

    const result = await this.FileRepository.findAndCount({
      where,
      skip: 1,
      take: 2,
      // order: { id: 1 },
    });
    const records = result[0];
    const total = result[1];
    // const records = result[0];
    return { total, records };
  }

  // 由于上云操作，所以最好还是手动劫持错误
  async delete(fileURL) {
    try {
      // 数据库中删除，在删七牛云
      await deleteWithQinniu(fileURL);
      return await this.FileRepository.update(
        {
          url: fileURL,
        },
        { delete_time: new Date() },
      );
    } catch (error) {
      // console.log('deleteFile', error);
      throw new BadRequestException(error.message);
    }
  }

  async uploadToQiniu(file) {
    try {
      const { originalname, mimetype, size, buffer } = file;
      /**
       * 手动判断
       */
      if (size > fileConf.size) {
        throw new BadRequestException('文件超出大小' + fileConf.size);
      }
      if (!fileConf.allowMintType.includes(mimetype)) {
        throw new BadRequestException('文件格式不正确');
      }
      // 开始上传
      const result = await uploadWithQiniu(buffer, fileName);
      // console.log('res', result);
      // 上传后，写入连接到数据库
      const db = new FileEntity();
      db.original_name = originalname;
      db.url = result;
      return await this.FileRepository.save(db);
    } catch (error) {
      // console.log(error);
      throw new BadRequestException(error.message);
    }
  }
}
